package com.damon;

import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.text.util.Linkify;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.damon.bussearch.db.StopFactory;
import com.feedback.UMFeedbackService;
import com.mobclick.android.MobclickAgent;

public class SettingsActivity extends PreferenceActivity implements
		OnPreferenceChangeListener, OnPreferenceClickListener, OnSharedPreferenceChangeListener {

	protected static final String TAG = "SettingsActivity";
	EditTextPreference etDefaultCity;  
    
    String aboutKey;
    String feedbackKey;
    String manageHistoryKey;
    String tipsKey;
    
    Preference about;
    Preference feedback;
    Preference manageHistory;
    Preference tips;
    
    ListView lvHistory;
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.addPreferencesFromResource(R.xml.settings);
		
		etDefaultCity = (EditTextPreference)findPreference("defaultcity");  
		etDefaultCity.setOnPreferenceChangeListener(this);  
		etDefaultCity.setOnPreferenceClickListener(this);   
		
		SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
		etDefaultCity.setSummary(sp.getString("defaultcity", "北京"));
		
	    aboutKey = "about";
	    feedbackKey = "feedback";
	    manageHistoryKey = "searchhistory";
//	    tipsKey = this.getResources().getString(R.string.tips_key);
//	    
		about= findPreference(aboutKey);
		feedback= findPreference(feedbackKey);
		manageHistory = findPreference(manageHistoryKey);
//		tips= findPreference(tipsKey);
//		
		about.setOnPreferenceClickListener(this);  
		feedback.setOnPreferenceClickListener(this);  
		manageHistory.setOnPreferenceClickListener(this); 
//		tips.setOnPreferenceClickListener(this);  
		
		lvHistory = new ListView(this);
	}

	@Override
	public boolean onPreferenceChange(Preference preference, Object arg1) {
		Log.v("SystemSetting", "preference is changed");
		Log.v("Key_SystemSetting", preference.getKey());
		
		if (preference.getKey().equals("defaultcity")) {
			etDefaultCity.setSummary((String) arg1);
			return true;
		} else {
			return false;
		}
		
	}

	@Override
	public boolean onPreferenceClick(Preference preference) {
		Log.v("SystemSetting", "preference is clicked");  
        Log.v("Key_SystemSetting", preference.getKey());  
        
        if(preference.getKey().equals(aboutKey)){
        	AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("关于应用");
			builder.setView(new AboutView(this));
			builder.setPositiveButton("OK",  new OnClickListener(){
				@Override
				public void onClick(DialogInterface dialog, int which) {
					//nothing
				}});
			builder.show();
        }else if(preference.getKey().equals(feedbackKey)){
        	Log.v("Key_SystemSetting", "feedback sdk open"); 
        	UMFeedbackService.openUmengFeedbackSDK(SettingsActivity.this);
        }else if(preference.getKey().equals(manageHistoryKey)){
        	Log.v("Key_SystemSetting", "manage history"); 
        	AlertDialog.Builder builder = new AlertDialog.Builder(SettingsActivity.this);
        	builder.setTitle("管理查询历史，长按删除");
        	
        	List<String> stops = null;
        	try{
        		stops = StopFactory.getInstance(SettingsActivity.this).getAllStops();
        	}catch(Exception e){
        		e.printStackTrace();
        	}
        	if(stops != null){
	        	ListAdapter adapter = new ArrayAdapter<String>(SettingsActivity.this, android.R.layout.simple_list_item_1, stops);
	        	lvHistory.setAdapter(adapter);
	        	lvHistory.setOnItemLongClickListener(manageHistoryListener);
	        	builder.setView(lvHistory);
	        	builder.setNegativeButton("确定", new OnClickListener(){
					@Override
					public void onClick(DialogInterface dialog, int which) {
					}});
	        	builder.show();
        	}else{
        		Toast.makeText(SettingsActivity.this, "查询历史为空", Toast.LENGTH_SHORT).show();
        	}
        }
//        else if(preference.getKey().equals(tipsKey)){
//        	ViewPager awesomePager = new ViewPager(this);
//			awesomePager.setAdapter(new TipsAdapter(this));
//			AlertDialog.Builder builder = new AlertDialog.Builder(this);
//			builder.setTitle(R.string.tips_title);
//			builder.setView(awesomePager);
//			builder.setPositiveButton(R.string.tips_always_show,  new OnClickListener(){
//				@Override
//				public void onClick(DialogInterface dialog, int which) {
//					SharedPreferences spdefault = PreferenceManager.getDefaultSharedPreferences(SettingsActivity.this);
//					spdefault.edit().putBoolean(Util.SHAREDPREFERENCE_KEY_SHOWTIPS, true).commit();
//				}});
//			builder.setNegativeButton(R.string.tips_never_show, new OnClickListener(){
//				@Override
//				public void onClick(DialogInterface dialog, int which) {
//					SharedPreferences spdefault = PreferenceManager.getDefaultSharedPreferences(SettingsActivity.this);
//					spdefault.edit().putBoolean(Util.SHAREDPREFERENCE_KEY_SHOWTIPS, false).commit();
//				}});
//			builder.show();
//        }
        else {  
            return false;  
        }  
        return true;  
	}

	@Override
	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
			String key) {
		Log.d(TAG,"key="+key);
		if (key.equals("defaultcity")) {
			String cityTemp = sharedPreferences.getString(key, null);
			etDefaultCity.setSummary(cityTemp);
		}
	}
	
	private class AboutView extends ScrollView{

		private LinearLayout baselayout;
		private ImageView appIcon;
		private TextView appNameAndVersion;
		private TextView updateInfo;
		private TextView appInfo;
		
		public AboutView(Context context) {
			super(context);
			baselayout = new LinearLayout(context);
			baselayout.setOrientation(LinearLayout.VERTICAL);
			baselayout.setPadding(10, 5, 10, 5);
			this.addView(baselayout);
			
			appIcon = new ImageView(context);
			appNameAndVersion = new TextView(context);
			appInfo = new TextView(context);
			updateInfo = new TextView(context);
			
			LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			lp.gravity= Gravity.CENTER_HORIZONTAL;
			
			baselayout.addView(appIcon,lp);
			baselayout.addView(appNameAndVersion,lp);
			baselayout.addView(appInfo,lp);
			baselayout.addView(updateInfo);
			
			appIcon.setImageResource(R.drawable.logo2);
			appNameAndVersion.setTextSize(20);
			try {
				PackageInfo info  = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
				String versionName = info.versionName;
				appNameAndVersion.setText("\n"+context.getResources().getString(R.string.app_name)+" "+versionName);
			} catch (NameNotFoundException e) {
				e.printStackTrace();
			}
			appInfo.setAutoLinkMask(Linkify.ALL);
			appInfo.setText(R.string.app_info);
		}
		
	}

	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	private OnItemLongClickListener manageHistoryListener =  new OnItemLongClickListener() {
		@Override
		public boolean onItemLongClick(AdapterView<?> arg0,
				View arg1, int arg2, long arg3) {
			String keyword = ((ArrayAdapter<String>)arg0.getAdapter()).getItem(arg2);
			StopFactory.getInstance(SettingsActivity.this).deleteStop(keyword);
			
			List<String> stops = null;
        	try{
        		stops = StopFactory.getInstance(SettingsActivity.this).getAllStops();
        	}catch(Exception e){
        		e.printStackTrace();
        	}
        	if(stops != null){
	        	ListAdapter adapter = new ArrayAdapter<String>(SettingsActivity.this, android.R.layout.simple_list_item_1, stops);
	        	lvHistory.setAdapter(adapter);
        	}else{
        		Toast.makeText(SettingsActivity.this, "查询历史为空", Toast.LENGTH_SHORT).show();
        	}
			return true;
		}
	};
}
